﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using BoldBrick.Core.Logging;
using BoldBrick.OneIntranet.HR.Properties;
using BoldBrick.OneIntranet.HR.Resources;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using BoldBrick.SharePoint.CommonControls.Extensions;
using System.Linq;

namespace BoldBrick.OneIntranet.HR.FieldTypes
{
	public class ListLookupControl : BaseFieldControl
	{
		private static readonly ILogger log = Logger.GetLogger(typeof(ListLookupControl));

		#region ------ Value ----------------------------------------------------------------------

		public override object Value
		{
			get
			{
				EnsureChildControls();
				
				if (this.dropDownList.SelectedItem == null || (!this.Field.Required && this.dropDownList.SelectedIndex == 0))
					return null;

				ListLookupValue value = new ListLookupValue(new Guid(this.dropDownList.SelectedItem.Value), this.dropDownList.SelectedItem.Text);
				return value;
			}
			set
			{
				EnsureChildControls();
				if (value != null)
				{
					ListLookupValue contentTypeLookupValue = new ListLookupValue(value.ToString());
					this.dropDownList.SelectedValue = contentTypeLookupValue.ListID.ToString();
				}
			}
		}

		#endregion

		#region ------ Controls -------------------------------------------------------------------

		protected HtmlGenericControl divError;
		protected DropDownList dropDownList;

		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			// create error div
			divError = new HtmlGenericControl("div")
						{
							ID = "divError"
						};
			divError.Style[HtmlTextWriterStyle.Color] = "red";
			divError.Style[HtmlTextWriterStyle.Display] = "none";
			this.Controls.Add(divError);

			
			// create main div
			HtmlGenericControl divMain = new HtmlGenericControl("div")
											{
												ID = "divMain"
											};
			this.Controls.Add(divMain);

			// create drop down
			dropDownList = new DropDownList
							{
								ID = "dropDownListLists"
							};
			divMain.Controls.Add(dropDownList);

			CreateListItems();
		}

		private void CreateListItems()
		{
			uint language = SPContext.Current.Web.Language;

			if (this.dropDownList.Items.Count > 0)
				return;

			
				
			bool isRequired = this.Field.Required;
			
			// add (none) item if field is not required
			if (!isRequired)
			{
				string itemNone = ResourceBuilder.GetResource("ListLookupControl_ItemNone_Title", language);
				this.dropDownList.Items.Add(new ListItem(itemNone, null));
			}

			// get content type if content type is set
			string contentTypeId = this.Field.GetCustomProperty<string>(Settings.Default.Field_ListLookup_CustomProperty_ContentTypeId_Name, null);

			SPContentTypeId spContentTypeId = SPContentTypeId.Empty;
			if (!string.IsNullOrEmpty(contentTypeId))
			{
				try
				{
					
					spContentTypeId = new SPContentTypeId(contentTypeId);
				}
				catch (Exception ex)
				{
					string message = ResourceBuilder.GetResource("ListLookupControl_Error_ContentTypeIdIsBad", language);
					ShowError(message);
					log.Write(LogLevel.Error, ex, "Creating of ContentTypeId object failed.");
					return;
				}
			}

			// convert child content types to list items
			List<ListItem> listItems = new List<ListItem>();
			
			SPListCollection listCollection = SPContext.Current.Web.Lists;
			foreach (SPList list in listCollection)
			{
				if (spContentTypeId == SPContentTypeId.Empty)
				{
					listItems.Add(new ListItem(list.Title, list.ID.ToString()));
					continue;
				}

				SPContentType contentType = list.ContentTypes.GetChildContentType(spContentTypeId);
				if (contentType != null)
				{
					listItems.Add(new ListItem(list.Title, list.ID.ToString()));
				}
			}

			ListItem[] listItemsArray = listItems
				.OrderBy(item => item.Text)
				.ToArray();

			this.dropDownList.Items.AddRange(listItemsArray);
		}

		#endregion

		#region ------ Display --------------------------------------------------------------------

		protected override void RenderFieldForDisplay(HtmlTextWriter output)
		{
			if (this.ItemFieldValue == null)
				return;

			ListLookupValue value = new ListLookupValue(this.ItemFieldValue.ToString());
			output.Write(value.ListName);
		}

		#endregion

		#region ------ Validation -----------------------------------------------------------------

		public override void Validate()
		{
			base.Validate();

			if (!this.Field.Required)
				return;

			if (this.Value == null)
				this.IsValid = false;
		}

		#endregion

		#region ------ Errors ---------------------------------------------------------------------

		private void ShowError(string message)
		{
			EnsureChildControls();
			
			divError.Style[HtmlTextWriterStyle.Display] = "block";
			divError.InnerText = message;
		}

		#endregion
	}
}
